﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Threading;
using System.IO;

namespace RenRenClient
{
    public static class WebRequestExtensions
    {
#if WINDOWS_PHONE
        private const int DefaultRequestTimeout = 10000*60;

        public static WebResponse GetResponse(this WebRequest request)
        {
            var dataReady = new AutoResetEvent(false);
            WebResponse response = null;
            var callback = new AsyncCallback(delegate(IAsyncResult asynchronousResult)
                {
                    response = request.EndGetResponse(asynchronousResult);
                    dataReady.Set();
                });
            request.BeginGetResponse(callback, request);
            //if (dataReady.WaitOne(DefaultRequestTimeout))
            //{
            //    return response;
            //}

            return null;
        }

        public static Stream GetRequestStream(this WebRequest request)
        {
            var dataReady = new AutoResetEvent(false);
            Stream stream = null;
            var callback = new AsyncCallback(delegate(IAsyncResult asynchronousResult)
            {
                stream = (Stream)request.EndGetRequestStream(asynchronousResult);
                dataReady.Set();
            });

            request.BeginGetRequestStream(callback, request);
            if (!dataReady.WaitOne(DefaultRequestTimeout))
            {
                return null;
            }

            return stream;
        }
#endif
    }
}
